package com.yc.io.file;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import org.springframework.http.HttpEntity;
import sun.net.www.http.HttpClient;

import java.io.*;
import java.net.*;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileTest1 {
	
	/**
	 * 获取目录下的所有文件
	 */
	public void dir() {
		File f = new File("F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试");
		File[] list = f.listFiles();
		for (File file : list) {
//			System.out.println(file.getName());
			System.out.println(file.getAbsolutePath());
		}
	}
	
	public void dir2() {
		String dir = "F:\\worksource\\JKCT\\HB\\temp\\testImg\\图片拼接1\\单独测试";
		Path dirPath = Paths.get(dir);
		
        try(DirectoryStream<Path> stream = Files.newDirectoryStream(dirPath)){
            for(Path e : stream){
                System.out.println(e.getFileName());
//                System.out.println(e.getParent());
//            	e.toFile().is
//                System.out.println(e.toString());
                
                
            }
        } catch (IOException e){
            
        }
	}
	
	/**
	 * 测试：用一个小文件去覆盖一个大文件，是完全替换还是会出问题
	 * @throws IOException 
	 */
	public void m3() throws IOException {
		String path1 = "G:\\workfile\\temp\\33.txt";
		String path2 = "G:\\workfile\\temp\\cc.jpg";
		InputStream is = null;
		OutputStream os = null;
		try {
			byte[] buf = new byte[1024];
			is = new FileInputStream(path1);
			os = new FileOutputStream(path2);
			int len = 0;
			while((len = is.read(buf)) != -1) {
				os.write(buf, 0, len);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			is.close();
			os.close();
		}
		
		
		
		
	}
	
	public void m4() {
		File f = new File("abc");
		System.out.println(f.length());
	}
	
	public void m5_fileList() {
		File f = new File("F:/000workfile/客户/南瑞/tomcat/logs");
		String[] list = f.list();
		for (String fileName : list) {
			System.out.println(fileName);
		}
	}

	public String readRileContent2(String fileName) {
		try {
			StringBuffer sbf = new StringBuffer();
			String encoding = "UTF-8";
			File file = new File(fileName);
			if (file.isFile() && file.exists()) { //判断文件是否存在
				InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);//考虑到编码格式
				BufferedReader bufferedReader = new BufferedReader(read);
				String lineTxt = null;
				while ((lineTxt = bufferedReader.readLine()) != null) {
					sbf.append(lineTxt);
				}
				read.close();
				return sbf.toString();
			} else {
				System.out.println("找不到指定的文件");
				return null;
			}
		} catch (Exception e) {
			System.out.println("读取文件内容出错");
			e.printStackTrace();
		}
		return null;
	}


	/**
	 * 读取网络地址:不行
	 */
	public void m2() {
		String url = "https://cdd-static-upy.chediandian.com/open/active/img/67ca9a6b2f0248be81b322c61fa4b2c5.jpg";
		File file = new File(url);
		System.out.println(file.length());
	}

	public void m5() {
		String url = "https://cdd-static-upy.chediandian.com/open/active/img/67ca9a6b2f0248be81b322c61fa4b2c5.jpg";
		byte[] b = getURLBytes(url);
		System.out.println(b.length);
	}

	public void m6() {
//		String fileUrl = "https://udmp-bucket-uat.pabos.com.cn/ddf0829e/UDMP-98af9d230368b726ceba359ced046b470be5f6b4e8-ddf0829e-20211117022200-00000001/1?attname=2021-11-15对账文件.csv&e=1637122920&token=RLo_DQh4W31NgmKQeW9gMBIbCfY5z5PexmZ7Zrnv:n2zypuLi5PT8Ys1Bu5snVBP9xfw=";
		String fileUrl = "https://bfiles-stg.pingan.com.cn/brcp/wefiles/cust/temp/temp_wefiles_udmp_download.do?project=BROP-PEPS&expiredTime=1640073604568&uuid=cfc77469501340cebe8277a71491046b&weFileToken=G%2BjkvQeJ6TmAb8y%2B8%2FSDfugz8li3mEZB6qEc2qs9CoMl7zRwujsibproboc8EGvHoUfD1zCTaDWvXaCvErO8FGrRemlYpCe4xDGofEWq00%2BDpLjKQwnitUioZVjTDPrHY5QHsJcnqLYG1IXudfNDLV6%2BImYsmslFZnr7e%2B8vVapnBlxdd3cX%2BAYgTi3zxWjjee%2F%2F49XWyNbb4amCH4kLgLe6SFljku0FPkRoR8Nod5w8lLmKtirT7IiE6Cgpt8lto1lnnEvpIQkmaxWOftLLqp7dEgqs2ORqZH2jFIJ4%2Ft2EtyePGqWX4Lp%2FR1wlfnvYm50hjEOG5P%2BKQjoWtW7ayg%3D%3D&fileId=Fc867f4376f144c3094a8b430ca900392";
		byte[] ib = null;
		try {
			ib = IoUtil.readBytes(URLUtil.url(fileUrl).openStream());
			FileOutputStream os = new FileOutputStream("D:\\source\\word\\项目\\other\\test1116.xlsx");
			os.write(ib);
			os.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void m7() {
//		String fileUrl = "https://udmp-bucket-uat.pabos.com.cn/ddf0829e/UDMP-98af9d230368b726ceba359ced046b470be5f6b4e8-ddf0829e-20211117022200-00000001/1?attname=2021-11-15对账文件.csv&e=1637122920&token=RLo_DQh4W31NgmKQeW9gMBIbCfY5z5PexmZ7Zrnv:n2zypuLi5PT8Ys1Bu5snVBP9xfw=";
		String fileUrl = "https://app.chediandian.com/imgcloud/bill/pingan@client@1637140611476.xlsx/1637659011738/c5570e3f93a15ced550e3fa6b3476c07";
		String dest = "D:\\source\\word\\项目\\other\\test1117.xlsx";
		System.out.println(HttpUtil.downloadFile(fileUrl, dest));
	}

	private byte[] getURLBytes(String uRL) {
		ByteArrayOutputStream outPut = new ByteArrayOutputStream();
		byte[] data = new byte[1024];
		try {
			// 创建URL
			URL url = new URL(uRL);
			// 创建链接
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(10 * 1000);

			if(conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
				return null;
			}
			InputStream inStream = conn.getInputStream();
			int len = -1;
			while ((len = inStream.read(data)) != -1) {
				outPut.write(data, 0, len);
			}
			inStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return outPut.toByteArray();
	}


	public static boolean httpDownload(String httpUrl, String saveFile) {
		//
		int bytesum = 0;
		int byteread = 0;
		URL url = null;
		try {
			url = new URL(httpUrl);
			java.net.Authenticator.setDefault(new java.net.Authenticator(){
				@Override
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication("wcadmin", "wcadmin".toCharArray());
				}
			});
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
			return false;
		}
		try {
			URLConnection conn = url.openConnection();
			InputStream inStream = conn.getInputStream();
			FileOutputStream fs = new FileOutputStream(saveFile);
			byte[] buffer = new byte[1204];
			while ((byteread = inStream.read(buffer)) != -1) {//
				bytesum += byteread;//
				System.out.println(bytesum);
				fs.write(buffer, 0, byteread);
			}
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}


//	public static String DownLoadPages(String urlsrc, String outpath) throws UnknownHostException {
//		// 输入流
//		InputStream in = null;
//		// 文件输出流
//		FileOutputStream out = null;
//		try{
//			HttpParams httpParams = new BasicHttpParams();
//			HttpConnectionParams.setConnectionTimeout(httpParams,5000); //设置连接超时为5秒
//			HttpClient client = new DefaultHttpClient(httpParams); // 生成一个http客户端发送请求对象
//			HttpGet httpget1 = new HttpGet(urlsrc); //对查询页面get
//			HttpResponse httpResponse1 = client.execute(httpget1); // 发送请求并等待响应
//			// 判断网络连接是否成功
//			System.out.println("状态码："+httpResponse1.getStatusLine().getStatusCode());
//			if (httpResponse1.getStatusLine().getStatusCode() != 200)
//				System.out.println("网络错误异常！!!!");
//			else
//				System.out.println("网络连接成功!!!");
//			httpget1.abort(); //关闭get
//			HttpGet httpget2 = new HttpGet("http://....../download? DownloadFileName=All=true"); //对下载链接get实现下载
//			HttpResponse httpResponse2 = client.execute(httpget2);
//			HttpEntity entity = httpResponse2.getEntity(); // 获取响应里面的内容
//			in = entity.getContent(); // 得到服务气端发回的响应的内容（都在一个流里面）
//			out = new FileOutputStream(new File(outpath));
//			byte[] b = new byte[1024];
//			int len = 0;
//			while((len=in.read(b))!= -1){
//				out.write(b,0,len);
//			}
//			in.close();
//			out.close();
//		}catch(Exception e){
//			e.printStackTrace();
//		}
//	}

	public void m8() {
		File f = new File("");

	}


	public static void main(String[] args) throws IOException {
		FileTest1 ft = new FileTest1();
//		ft.dir();
//		ft.dir2();
//		ft.m3();
//		ft.m4();
//		ft.m5_fileList();
//		String str = ft.readRileContent2("D:\\source\\word\\项目\\代步车\\base64.txt");
//		System.out.println(str);
//		ft.m2();
//		ft.m5();
		ft.m6();
//		ft.m7();
	}

}
